package go_ioc

import (
	"reflect"
)

type beanContainer struct {
	beanMapper     map[reflect.Type]reflect.Value
	beanNameMapper map[string]reflect.Value
}

func newBeanContainer() *beanContainer {
	return &beanContainer{
		beanMapper:     make(map[reflect.Type]reflect.Value),
		beanNameMapper: make(map[string]reflect.Value),
	}
}

func (this beanContainer) GetBeanMapper() map[reflect.Type]reflect.Value {
	return this.beanMapper
}

func (this beanContainer) GetBeanNameMapper() map[string]reflect.Value {
	return this.beanNameMapper
}

/**
添加到容器
*/
func (this beanContainer) add(bean interface{}) error {
	t := reflect.TypeOf(bean)
	if t.Kind() != reflect.Ptr {
		return IOC_ERROR_NOT_PRT
	}
	_, ok := this.beanMapper[t]
	_, ks := this.beanNameMapper[t.Elem().Name()]
	if ok || ks {
		return nil
	}
	rv := reflect.ValueOf(bean)
	this.beanMapper[t] = rv
	this.beanNameMapper[t.Elem().Name()] = rv
	return nil
}

/**
获取容器值
*/
func (this beanContainer) get(bean interface{}) reflect.Value {
	var t reflect.Type
	if v, ok := bean.(reflect.Type); ok {
		t = v
	} else {
		t = reflect.TypeOf(bean)
	}
	if v, ok := this.beanMapper[t]; ok {
		return v
	}
	for k, v := range this.beanMapper {
		if t.Kind() == reflect.Interface && k.Implements(t) {
			return v
		}
	}
	return reflect.Value{}
}

func (this beanContainer) getName(beanName string) reflect.Value {
	//t := reflect.TypeOf(bean)
	//if t.Kind() != reflect.Ptr {
	//	return reflect.Value{}
	//}
	//tName := t.Elem().Name()
	if v, ok := this.beanNameMapper[beanName]; ok {
		return v
	}
	return reflect.Value{}

}

/**
删除一个
*/
func (this beanContainer) delete(bean interface{}) {

}
